package com.joven.security.service.impl;

import com.alibaba.fastjson.JSON;
import com.joven.security.dao.SysUserDao;
import com.joven.security.model.LoginUser;
import com.joven.security.model.SysUser;
import com.joven.security.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author wzj
 * @Date 2023-03-01 15:26
 **/
@Slf4j
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    RedisUtils redisUtils;

    @Resource
    SysUserDao sysUserDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StringUtils.isEmpty(username)) {
            log.error("username不能为空！");
            return null;
        }
        SysUser sysUser = sysUserDao.selectByUserName(username);
        if (sysUser == null) {
            throw new RuntimeException("用户不存在！");
        }
        List<String> sysMenus = sysUserDao.selectMenusByUserId(sysUser.getId());
        log.info("根据user:{}查询权限结果为：{}", JSON.toJSONString(sysUser), JSON.toJSONString(sysMenus));
        return new LoginUser(sysUser, sysMenus);
    }
}
